//
//  ClubGameForumViewController.swift
//  77Club
//
//  Created by Apple on 2024/11/4.
//

import UIKit
import JXSegmentedView
import ZLPhotoBrowser

private let headerID    = "ClubGameForumHeaderView"

class ClubGameForumViewController: ClubBaseViewController {

    private var topView = ClubGameForumTopView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .white
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubGameForumCell.self)
        tableView.register(ClubGameForumHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 100.0.Scale
//        tableView.estimatedSectionHeaderHeight = 0
        tableView.sectionFooterHeight = 0
        tableView.contentInset = UIEdgeInsets.zero
        tableView.sectionHeaderTopPadding = 0
        return tableView
    }()
    private var emptyView = ClubEmptyView()
    private var releaseButton = c_make_ex(UIButton.self)
        .image("Square_add").end()
    
    var communityId: String = "" {
        didSet{
            loadData()
        }
    }
    var gameModel: ClubGameDetailModel?
    private var model: ClubGameCommunityModel?
    private var dataSource: [ClubGameCommunityListModel]?
    private var pageIndex = 1
    private var sortby = "1"
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        releaseButton.isHidden = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        releaseButton.isHidden = true
    }
    
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//       
//    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .clear
        loadData()
        view.subviews{
            topView
            tableView
            emptyView
        }
        
        topView.leading(0).trailing(0).top(0).height(104.0.Scale)
        tableView.leading(0).trailing(0).bottom(0)
        tableView.Top == topView.Bottom
        emptyView.leading(0).trailing(0).top(.navi_height + 165).height(200)
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
        emptyView.titleString = "暂无帖子，快去发一篇吧~"
        emptyView.isHidden = true
        releaseButton.addTarget(self, action: #selector(clickAddButton), for: .touchUpInside)
        self.view.addSubview(releaseButton)
        let panGesture = UIPanGestureRecognizer(target: self, action:#selector(dragAction(gesture:)))
        releaseButton.addGestureRecognizer(panGesture)
        releaseButton.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.width.equalTo(88.0.Scale)
            make.height.equalTo(88.0.Scale)
            make.bottom.equalTo(-CGFloat.tabBar_height)
        }
    }


}

extension ClubGameForumViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubGameForumCell", for: indexPath) as! ClubGameForumCell
        cell.model = dataSource?[indexPath.row]
        cell.jumpToDetail = {postId, uid in
            self.toDetailVC(newId: postId, uid: uid)
        }
        cell.didSelectImage = { index,images in
            self.selectImage(index: index, images: images)
        }
        cell.didSelectVideo = { url in
            self.selectVideo(url: url)
        }
        cell.likeBlock = {
            self.loadNewData()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let newId = self.dataSource?[indexPath.row].id ?? ""
        let uid = self.dataSource?[indexPath.row].uid ?? ""
        self.toDetailVC(newId: newId, uid: uid)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubGameForumHeaderView
        header.titleString = "全部帖子"
        header.updateDataBlock = { type in
            self.sortby = type
            self.loadNewData()
        }
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if dataSource?.count ?? 0 == 0 {
            return 0
        }
        return 44.0.Scale
    }
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
}

//MARK: action
extension ClubGameForumViewController {
    
    private func toDetailVC(newId: String, uid: String){
        
        if uid != "0" {
            //用户
            let detailVC = ClubGameForumDetailViewController()
            detailVC.postID = newId
            detailVC.pid = self.communityId
            detailVC.gameModel = self.gameModel
            detailVC.likeBlock = {
                self.loadNewData()
            }
            detailVC.updateDataBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }else{
            //官方
            let detailVC = ClubForumDetailViewController()
            detailVC.newId = newId
            detailVC.likeBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        
    }
    
    @objc private func dragAction(gesture: UIPanGestureRecognizer) {
        
        // 移动状态
        let moveState = gesture.state
        switch moveState {
        case .began:
            break
        case .changed:
            // floatBtn 获取移动轨迹
            let point = gesture.translation(in: self.view)
            self.releaseButton.center = CGPoint(x: self.releaseButton.center.x + point.x, y: self.releaseButton.center.y + point.y)
            break
        case .ended:
            // floatBtn 移动结束吸边
            let point = gesture.translation(in: self.view)
            var newPoint = CGPoint(x: self.releaseButton.center.x +  point.x, y: self.releaseButton.center.y + point.y)
            if newPoint.x < .screenWidth / 2.0 {
                newPoint.x = self.releaseButton.bounds.width/2 + 17.0.Scale
            } else {
                newPoint.x = .screenWidth - self.releaseButton.bounds.width/2 - 17.0.Scale
            }
            if newPoint.y <= self.releaseButton.bounds.height/2 + 17.0.Scale + .navi_height{
                newPoint.y = self.releaseButton.bounds.height/2 + 17.0.Scale + .navi_height
            } else if newPoint.y >= self.view.bounds.height - self.releaseButton.bounds.height/2 - 17.0.Scale {
                newPoint.y = self.view.bounds.height - self.releaseButton.bounds.height/2 - 17.0.Scale
            }
            // 0.5秒 吸边动画
            UIView.animate(withDuration: 0.5) {
                self.releaseButton.center = newPoint
            }
            break
        default:
            break
        }
        // 重置 panGesture
        gesture.setTranslation(.zero, in: self.view)
    }
    
    @objc private func clickAddButton() {

        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            let pushVC = ClubPushStrategyViewController()
            pushVC.type = "4"
            pushVC.communityId = self.communityId
            pushVC.updateDataBlock = {
                self.loadData()
            }
            self.present(pushVC, animated: true)
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
}


//MARK: Data
extension ClubGameForumViewController {
    
    private func loadData(){
        Task {
            ToastUtil.show()
            let res = await network.request(.communityTop(communityID: communityId),type: ClubGameCommunityModel.self)
            
            if res.isSuccess, let model = res.model {
                self.topView.model = model
                self.topView.communityId = communityId
                self.model = model
                self.loadPostList()
            }
        }
    }
    
    private func loadPostList(){
        
        Task {
            let res = await network.request(.communityPostList(communityID: communityId, type: "4", sortby: sortby, page: pageIndex),type: ClubGameCommunityListModel.self)
            tableView.refresh_end()
            ToastUtil.dismiss()
            if res.isSuccess, let models = res.models {
                self.dataSource = models
                self.emptyView.isHidden = models.count > 0
                tableView.reloadData()
            }
        }
    }
    
    @objc func loadNewData(){
        pageIndex = 1
        loadPostList()
    }
    
    @objc func loadMoreData(){

        pageIndex += 1
        Task {
            let res = await network.request(.communityPostList(communityID: communityId, type: "4", sortby: sortby, page: pageIndex),type: ClubGameCommunityListModel.self)
            tableView.refresh_end()
            ToastUtil.dismiss()
            if res.isSuccess, let models = res.models {
                self.dataSource?.append(contentsOf: models)
                tableView.reloadData()
            }
        }
    }
}


extension ClubGameForumViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
